<template>
  <div>
    <el-divider content-position="left">basic information</el-divider>
    <el-form ref="logisticsForm" size="small" :model="entity" :rules="rules" label-width="200px">
      <el-form-item label="logistics No" prop="wuliuno">
        <el-input v-model="entity.wuliuno" placeholder="logistics No" />
      </el-form-item>
      <el-form-item label="logistics title" prop="wuliuname">
        <el-input v-model="entity.wuliuname" placeholder="logistics title" />
      </el-form-item>
      <el-form-item label="transportation company" prop="companyuser" v-if="checkYuanGong">
        <el-select v-model="entity.companyuser" filterable placeholder="please select">
          <el-option v-for="item in wlUserList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form ref="logisticsStepForm" size="small" label-width="220px">
      <el-form-item>
        <el-button type="success" size="mini" @click="addStep('produce step')" style="float: right">add step</el-button>
      </el-form-item>
      <el-form-item label="step title" prop="stepname" v-for="(item,index) in stepList" :key="index + '-' + item.id">
        <el-input v-model="item.stepname" placeholder="step title" >
          <template slot="append">
            <el-popconfirm confirmButtonText='ok' cancelButtonText='cancel'
                           icon="el-icon-info" iconColor="red"
                           title="confirm delete?" @confirm="deleteStep(item.id, index)">
              <el-button slot="reference" type="danger" icon="el-icon-delete"></el-button>
            </el-popconfirm>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24" style="text-align: center">
        <el-button type="primary" native-type="submit" @click="btnLogisticsSubmit">save</el-button>
      </el-col>
    </el-row>

    <div v-if="entity.id">
      <el-divider content-position="left">freight information</el-divider>
      <el-form ref="wuLiuProductForm" size="small" label-width="200px">
        <el-form-item :label="item.productname + '-' + item.productguige"  v-for="(item,index) in wuLiuProductList" :key="index + '-' + item.id">
          <el-input v-model="item.shuLiang" placeholder="please input count" οninput="value=value.replace(/^0+(\d)|[^\d]+/g,'')" type="number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" @click="btnFreightSubmit">save freight</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import PermissionType from "../../utils/PermissionType";
export default {
  props:{
    wuLiuId : {type : Number, default: 0},
    orderid : {type : Number, default: 0}
  },
  data() {
    return {
      PermissionType : PermissionType,
      entity: {
        id : this.wuLiuId,
        orderid : this.orderid,
        wuliuno: '',
        wuliuname: '',
        companyuser: undefined,
        companyname: ''
      },
      wlUserList:[],
      rules: {
        wuliuno: [
          { required: true, message: 'please input logistics No', trigger: 'blur' },
          { min: 4, max: 100, message: 'Between 4 and 20 characters in length',  trigger: 'blur' }
        ],
        wuliuname: [
          { required: true, message: 'please input logistics title', trigger: 'blur' },
          { min: 4, max: 100, message: 'Between 4 and 20 characters in length',  trigger: 'blur' }
        ],
        companyuser: [
          { required: true, message: 'please select logistics user', trigger: 'blur' },
        ],
      },
      stepList:[],
      wuLiuProductList:[],
    }
  },
  computed : {
    checkYuanGong(){
      const permissions = this.$store.getters['user/permissions']
      return permissions.includes(PermissionType.yuanGong)
    }
  },
  mounted() {
    this.loadWLUser();
    this.loadEntity();
    this.loadStep();
    this.loadLogisticsProduct();
  },
  methods: {
    loadWLUser(){
      if(this.checkYuanGong){
        request({ url: '/emp/wluser/listallwluser', data: {} }).then( res =>{
          this.wlUserList = res.data
        })
      }
    },
    loadEntity(){
      if(this.wuLiuId > 0){
        request({ url: '/emp/orderwuliu/getwuliu', data: {id : this.wuLiuId} }).then( res =>{
          this.entity = res.data
        })
      }
    },
    /*运输单运输的产品货物数量*/
    loadLogisticsProduct(){
      request({ url: '/emp/orderwuliu/listwuliuproduct', data: {orderId : this.orderid, wuLiuId : this.wuLiuId} }).then( res =>{
        this.wuLiuProductList = res.data
      })
    },
    /*物流步骤*/
    loadStep(){
      if(this.wuLiuId > 0){
        request({ url: '/emp/orderwuliu/listwuliustep', data: {wuLiuId:this.wuLiuId} }).then( res =>{
          this.stepList = res.data
          if(this.stepList.length === 0){
            this.stepList.push({stepname:'logistics step', sortid:0, orderwuliuid:this.wuLiuId, id:0})
          }
        })
      }else{
        this.stepList.push({stepname:'logistics step', sortid:0, orderwuliuid:this.wuLiuId, id:0})
      }
    },
    addStep(){
      let sortIdArray = this.stepList.map((val) => val.sortid)
      sortIdArray.sort((a,b)=>a-b);
      const maxSortId = sortIdArray[sortIdArray.length -1];
      this.stepList.push({stepname: 'logistics step', sortid:(maxSortId + 100), orderwuliuid:this.wuLiuId, id:0})
    },
    deleteStep(id, index){
      if(id>0){
        request({ url: '/emp/orderwuliu/deletewuliustop', data: {id:id} }).then( res =>{
          this.stepList = this.stepList.filter((s,i)=>i!==index)
        })
      }else{
        this.stepList = this.stepList.filter((s,i)=>i!==index)
      }
      this.wuLiuId > 0 ? this.$EventBus.$emit("wuliuedit", {}):this.$EventBus.$emit("wuliuadd", {})
    },
    btnLogisticsSubmit(){
      this.$refs['logisticsForm'].validate((valid) => {
        if(valid){
          this.entity.stepList = this.stepList
          request({
            url: '/emp/orderwuliu/addeditwuliu',
            data: this.entity
          }).then( res =>{
            if(res.code === "200"){
              this.$message.success(res.msg)
              //this.$emit('update:visible', false);  //关闭弹窗
              //触发事件总线，让列表界面更新数据
              this.wuLiuId > 0 ? this.$EventBus.$emit("wuliuedit", {}):this.$EventBus.$emit("wuliuadd", {})
              this.entity.id = res.data.id;
            }else{
              this.$message.error(res.msg);
            }
          })
        }else{
          console.log('error submit!!');
          return false;
        }
      })
    },
    btnFreightSubmit(){
      if(this.entity.id === 0){
        this.$message.error('please save basic information first');
        return
      }
      request({
        url: '/emp/orderwuliu/savewuliuproduct',
        data: {wuLiuId : this.entity.id, wuLiuProductList : this.wuLiuProductList}
      }).then(res =>{
        this.$message.success(res.msg)
        //this.$emit('update:visible', false);  //关闭弹窗
        this.wuLiuId > 0 ? this.$EventBus.$emit("wuliuedit", {}):this.$EventBus.$emit("wuliuadd", {})
      })
    }
  }
}
</script>

<style scoped>

</style>
